<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ReturnCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CustomerMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected HttpResponse $response;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $print_start_time = microtime_str();
        
        try {
            $response = $handler->handle($request);
        } catch (\Exception $exception) {
            $result = [
                'code' => ReturnCode::SERVER_ERROR->value,
                'msg'  => ReturnCode::getMessage(ReturnCode::SERVER_ERROR),
                'data' => [
                    'message' => $exception->getMessage(),
                    'file'    => $exception->getFile(),
                    'line'    => $exception->getLine()
                ]
            ];

            return $this->response->json($result);
        } finally {
            $print_end_time = microtime_str();

            print_r(sprintf("\r\n||==============================================================================================================|| \r\n"));
            print_r(sprintf("* 当前运行的PHP版本 : %s .\r\n", PHP_VERSION));
            print_r(sprintf("* 开始执行时间 : %s .\r\n", $print_start_time));
            print_r(sprintf("* 请求地址 : %s, 请求方式 : %s .\r\n", $this->request->getUri(), $this->request->getMethod()));
            print_r(sprintf("* 请求头 : %s\r\n", json_encode($this->request->getHeaders(), JSON_UNESCAPED_UNICODE)));
            print_r(sprintf("* 请求参数 : %s\r\n", json_encode($this->request->all(), JSON_UNESCAPED_UNICODE)));
            print_r(sprintf("* 执行结束时间 : %s .\r\n", $print_end_time));
            print_r(sprintf("||==============================================================================================================|| \r\n\r\n"));
        }

        return $response;
    }
}
